#include <head.h>
#define MAX_THREAD_CNT  (5)
pthread_mutex_t m[MAX_THREAD_CNT];
void *tfn(void *p);
int philosopher_main(int argc ,char** argv)
{
    pthread_t t[MAX_THREAD_CNT];
    for(int i=0;i<MAX_THREAD_CNT;i++){
        pthread_mutex_init(&(m[i]),NULL);
    }
    for(int i=0;i<MAX_THREAD_CNT;i++){
        pthread_create(&(t[i]),NULL,tfn,(void*)i);
    }

    for(int i=0;i<MAX_THREAD_CNT;i++){
        pthread_join(t[i],NULL);
    }
    for(int i=0;i<MAX_THREAD_CNT;i++){
        pthread_mutex_destroy(&(m[i]));
    }

    return 0;
}
void *tfn(void *p)
{
    int value  =(int )p;
    int cnt =5;
    int l =0,r=0;
    srand(time(NULL));
    if(value == MAX_THREAD_CNT -1){
        l =0;
        r= value;
    }
    else{
        l =value;
        r= value+1;

    }
    while (1)
    {
        pthread_mutex_lock(&(m[l]));
        if(pthread_mutex_trylock(&(m[r]))==0){
            printf("\t %c is eating!\n",value+'A');
            pthread_mutex_unlock(&(m[r]));
        }
        pthread_mutex_unlock(&(m[l]));
        sleep(rand()%5);
    }
    
    return NULL;
}